// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-08-01

package src

import (
	"context"
	"fmt"
	"gitee.com/go-libs/log"
)

type (
	TransactionHandler func(ctx context.Context, session *Session) error
)

func Transaction(ctx context.Context, handlers ...TransactionHandler) (err error) {
	var session *Session

	// Creates
	// a master connect session.
	if session, err = Config.GetMaster(ctx); err != nil {
		return
	}

	// Close
	// session when done.
	defer func() {
		if se := session.Close(); se != nil {
			log.Infofc(ctx, `transaction session close error: %v`, se)
		}
	}()

	// Schedule to executor with a master session.
	err = TransactionWithSession(ctx, session, handlers...)
	return
}

func TransactionWithSession(ctx context.Context, session *Session, handlers ...TransactionHandler) (err error) {
	// Close auto commit.
	if _, err = session.Context(ctx).Exec("SET AUTOCOMMIT = 0"); err != nil {
		return
	}

	// Open transaction.
	if err = session.Context(ctx).Begin(); err != nil {
		return
	}

	// Executed when process done.
	defer func() {
		// Catch
		// runtime panic and recover it.
		if r := recover(); r != nil {
			log.Fatalfc(ctx, `transaction panic: %v`, r)
			err = fmt.Errorf(`r`)
		}

		// End transaction with rollback or commit.
		if err != nil {
			if se := session.Context(ctx).Rollback(); se != nil {
				log.Errorfc(ctx, "transaction rollback error: %v", se)
			}
		} else {
			if se := session.Context(ctx).Commit(); se != nil {
				log.Errorfc(ctx, "transaction commit error: %v", se)
			}
		}

		// Reopen auto commit.
		_, _ = session.Context(ctx).Exec("SET AUTOCOMMIT = 1")
	}()

	// Range handlers.
	for _, handler := range handlers {
		if err = handler(ctx, session); err != nil {
			break
		}
	}
	return
}
